package com.bestillet.defaultmultishop;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class CampaignActivity extends Activity {
	private DrawerLayout layout;
	private ProgressBar progress;
	private ListView sidemenu;
	private ImageView image;
	private TextView message, restaurant, address, hours, open, header, text, obs;
	private Button back, proceed, settings;
	private Context context;

	private SharedPreferences preferences;
	private ShopApplication app;
	private ImageTask iTask;
	private ShopTask task;
	private Campaign campaign;
	
	private String[] items;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_campaign);

		preferences = getSharedPreferences("DefaultShop", MODE_PRIVATE);
		app = (ShopApplication) getApplicationContext();
		context = this;
		
		progress = (ProgressBar) findViewById(R.id.progressBar1);
		
		items = new String[] { "Info", "Indstillinger", "Genbestil ordre" };
		
		layout = (DrawerLayout) findViewById(R.id.drawer_layout);
        sidemenu = (ListView) findViewById(R.id.left_drawer);
        
        sidemenu.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, items));
        sidemenu.setOnItemClickListener(new DrawerItemClickListener());
		
		image = (ImageView) findViewById(R.id.imgCampaign);
		message = (TextView) findViewById(R.id.lblMessage);
		restaurant = (TextView) findViewById(R.id.lblRestaurant);
		address = (TextView) findViewById(R.id.lblAddress);
		hours = (TextView) findViewById(R.id.lblHours);
		open = (TextView) findViewById(R.id.lblOpen);
		text = (TextView) findViewById(R.id.lblCampaignText);
		obs = (TextView) findViewById(R.id.lblCampaignObs);
		header = (TextView) findViewById(R.id.lblCampaignHeader);
		
		back = (Button) findViewById(R.id.btnCampaignBack);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		proceed = (Button) findViewById(R.id.btnContinue);
		proceed.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), CategoryActivity.class);
				startActivity(intent);
			}
		});
		
		settings = (Button) findViewById(R.id.btnSettings);
		settings.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				layout.openDrawer(sidemenu);
			}
		});
		
		progress.setVisibility(View.VISIBLE);
		proceed.setVisibility(View.INVISIBLE);
		
		task = new ShopTask();
		task.execute();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (task != null)
			if (task.getStatus() == Status.RUNNING)
				task.cancel(true);

		if (iTask != null)
			if (iTask.getStatus() == Status.RUNNING)
				iTask.cancel(true);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		Calendar date = Calendar.getInstance();
		Calendar deadline = app.getShop().getDeadline();
		if (date.get(Calendar.YEAR) != deadline.get(Calendar.YEAR) || date.get(Calendar.MONTH) != deadline.get(Calendar.MONTH) || date.get(Calendar.DAY_OF_MONTH) != deadline.get(Calendar.DAY_OF_MONTH)) {
			Intent intent = new Intent(this, ShopActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
	}
	
	private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {
    	switch (position) {
		case 0:
			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(Server.INFO + app.getShop().getIdx()));
			startActivity(browserIntent);
			break;
		case 1:
			Intent customer = new Intent(this, CustomerActivity.class);
			startActivity(customer);
			break;
		case 2:
			Intent order = new Intent(this, OrderActivity.class);
			startActivity(order);
			break;
		default:
			Intent card = new Intent(this, CardActivity.class);
			card.putExtra("index", position - 3);
			startActivity(card);
			break;
		}
    	
        sidemenu.setItemChecked(position, false);
        layout.closeDrawer(sidemenu);
    }
	
	private class ShopTask extends AsyncTask<Void, Void, Boolean> {
    	@Override
		protected Boolean doInBackground(Void... params) {
    		InputStream in;
			try {
				// Get basketId
				String phone = preferences.getString("phone", "");
				in = Server.post(Server.BASKETID, Server.getAuthenticationBasketId(phone, app.getShop().getIdx()));
				XmlPullParser parser = Server.toXmlParser(in);
				app.setBasketId(XmlParser.getBasketId(parser));
				
				// Get cards
				app.clearCards();
				in = Server.post(Server.CARDS, Server.getAuthenticationCard(app.getShop().getIdx()));
    			parser = Server.toXmlParser(in);
    			ArrayList<Card> cards = XmlParser.getCards(parser);
    			app.addCards(cards);
				
				// Get campaign
				in = Server.post(Server.CAMPAIGN, Server.getAuthenticationCampaign(app.getShop().getIdx()));
    			parser = Server.toXmlParser(in);
    			campaign = XmlParser.getCampaign(parser);
    			
    			// Close connection
    			in.close();
			} catch (IOException e) {
    			Log.e("Shop", "IOException: " + e.getMessage());
				return false;
			} catch (XmlPullParserException e) {
    			Log.e("Shop", "XmlPullParserException: " + e.getMessage());
				return false;
			} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
    			return false;
    		} catch (IllegalArgumentException e) {
    			Log.e("Shop", "IllegalArgumentException: " + e.getMessage());
    			return false;
    		}
    		return true;
    	}
    	
    	@Override
	    protected void onPostExecute(Boolean success) {
			progress.setVisibility(View.GONE);
    		if (success) {
    			// Set shop info
    			header.setTextColor(Color.parseColor(app.getShop().getHexColor()));
    			message.setText(getResources().getString(R.string.campaign_message));
    			restaurant.setText(app.getShop().getName());
    			address.setText(app.getShop().getAddress() + ", " + app.getShop().getZipcode() + " " + app.getShop().getCity());
    			
    			// Set campaign
    			if (campaign != null)
    	    	{
    		    	if (campaign.getIdx() != -1) {
    		    		// Set campaign info
    		    		image.setImageBitmap(campaign.getImage());
    		    		header.setText(Html.fromHtml(campaign.getHeader().replace("\\n", "<br>").toUpperCase(Locale.ENGLISH)));
    		    		text.setText(Html.fromHtml(campaign.getMessage().replace("\\n", "<br>")));
    		    		obs.setText(Html.fromHtml(campaign.getObs().replace("\\n", "<br>")));
    		    		
    	    			// Get campaign picture
    	    			if (campaign.getIdx() != -1 && campaign.getPicture().length() > 0) {
    		    			Bitmap b = app.getBitmapFromMemCache(campaign.getPicture());
    						if (b != null) {
    							if (b.isRecycled()) {
    								app.removeBitmapFromMemoryCache(campaign.getPicture());
    								iTask = new ImageTask();
    								iTask.execute(Server.CAMPAIGN_IMAGES + campaign.getPicture(), campaign.getPicture());
    							} else {
    								image.setImageBitmap(b);
    								image.setVisibility(View.VISIBLE);
    							}
    						} else {
    							iTask = new ImageTask();
    							iTask.execute(Server.CAMPAIGN_IMAGES + campaign.getPicture(), campaign.getPicture());
    						}
    	    			}
    		    	}
    	    	}
    			
    			// Set menu
    			items = new String[3 + app.getCards().size()];
    			for (int i = 0; i < 3 + app.getCards().size(); i++) {
    				switch (i) {
    				case 0:
    					items[i] = "Info";
    					break;
    				case 1:
    					items[i] = "Indstillinger";
    					break;
    				case 2:
    					items[i] = "Genbestil ordre";
    					break;
    				default:
    					items[i] = app.getCards().get(i - 3).getName();
    					break;
    				}
    			}
    	        sidemenu.setAdapter(new ArrayAdapter<String>(context, R.layout.drawer_list_item, items));
    			
    			// Check if shop is closed and handle the situation
    			if (app.getShop().getHours().equals("Lukket") || app.getShop().getOrders().equals("Lukket")) {
    		    	header.setText(R.string.campaign_closed);
    				text.setText(app.getShop().getClosed());
    				proceed.setVisibility(View.INVISIBLE);
    				iTask = new ImageTask();
    				iTask.execute(Server.CAMPAIGN_IMAGES + app.getShop().getPicture(), app.getShop().getPicture());
    			} else {
    				proceed.setVisibility(View.VISIBLE);
        			hours.setText(Html.fromHtml(getResources().getString(R.string.campaign_hours) + " <b>" + app.getShop().getHours() + "</b>"));
        			open.setText(Html.fromHtml(getResources().getString(R.string.campaign_open) + " <b>" + app.getShop().getOrders() + "</b>"));
    			}
    		} else {
    			AlertDialog.Builder builder = new AlertDialog.Builder(context);
	    		builder.setMessage(R.string.error_shops)
	    		       .setTitle(R.string.error)
	    		       .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								task = new ShopTask();
								task.execute();
								progress.setVisibility(View.VISIBLE);
								proceed.setVisibility(View.INVISIBLE);
							}
						})
						.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						});
	    		AlertDialog dialog = builder.create();
	    		dialog.show();
    		}
    	}
	}
	
	private class ImageTask extends AsyncTask<String, Void, Boolean> {
		private Bitmap b;
		
    	@Override
		protected Boolean doInBackground(String... params) {
    		try {
    			String url = params[0];
    			String name = params[1];
    			InputStream in = Server.get(url);
    			b = Server.downloadBitmap(in, (Activity)context);
    			in.close();
    			app.addBitmapToMemoryCache(name, b);
			} catch (IOException e) {
    			Log.e("Shop", "IOException: " + e.getMessage());
				return false;
			} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
				return false;
			} catch (OutOfMemoryError e) {
    			Log.e("Shop", "OutOfMemoryError: " + e.getMessage());
				return false;
			}
    		return true;
    	}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
			image.setImageBitmap(b);
			image.setVisibility(b == null ? View.GONE : View.VISIBLE);
	    }
	}
}
